﻿using ZR.Model;
using ZR.Repository;

namespace ZR.ServiceCore
{
    /// <summary>
    /// 基础服务定义
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseService<T> : BaseRepository<T> where T : class, new()
    {
        #region 构建前端所需要树结构

        /// <summary>
        /// 构建前端所需要树结构
        /// </summary>
        /// <param name="list">列表</param>
        /// <returns></returns>
        protected List<TreeNodeInfo> BuildTree(List<TreeNodeInfo> list)
        {
            List<TreeNodeInfo> returnList = new List<TreeNodeInfo>();
            List<string> allIds = list.Select(f => f.Id).ToList();
            foreach (var dept in list)
            {
                // 如果是顶级节点, 遍历该父节点的所有子节点
                if (!allIds.Contains(dept.PaId))
                {
                    FillChildren(list, dept);
                    returnList.Add(dept);
                }
            }

            if (!returnList.Any())
            {
                returnList = list;
            }
            return returnList;
        }

        /// <summary>
        /// 填充子结点
        /// </summary>
        /// <param name="list"></param>
        /// <param name="t"></param>
        private void FillChildren(List<TreeNodeInfo> list, TreeNodeInfo t)
        {
            //得到子节点列表
            List<TreeNodeInfo> childList = GetChildList(list, t);
            t.Children = childList;
            foreach (var item in childList)
            {
                if (GetChildList(list, item).Count() > 0)
                {
                    FillChildren(list, item);
                }
            }
        }

        /// <summary>
        /// 递归获取子结点
        /// </summary>
        /// <param name="list">所有结点</param>
        /// <param name="item">结点</param>
        /// <returns></returns>
        private List<TreeNodeInfo> GetChildList(List<TreeNodeInfo> list, TreeNodeInfo item)
        {
            return list.Where(p => p.PaId == item.Id).ToList();
        }

        #endregion
    }
}
